<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :esc-to-close="false"
    :width="width >= 1200 ? 1200 : '100%'"
    draggable
    :align-center="true"
    @before-ok="save"
    @close="reset"
  >
    <div class="detail_content" style="display: flex; flex-direction: column;">
      <GiForm ref="formRef" v-model="form" :columns="columns">
        <template #noticeUsers>
          <a-select
            v-model="form.noticeUsers"
            :options="userList"
            multiple
            :max-tag-count="4"
            :allow-clear="true"
          />
          <a-tooltip content="选择用户">
            <a-button @click="onOpenSelectUser">
              <template #icon>
                <icon-plus />
              </template>
            </a-button>
          </a-tooltip>
        </template>
      </GiForm>
      <div style="flex: 1;">
        <AiEditor v-model="form.content" />
      </div>
    </div>

    <a-modal
      v-model:visible="selectUserModalVisible"
      title="用户选择"
      :mask-closable="false"
      :esc-to-close="false"
      :width="width >= 1200 ? 1200 : '100%'"
      draggable
      :align-center="true"
      @close="clear"
    >
      <UserSelect v-if="selectUserModalVisible" ref="UserSelectRef" v-model:value="form.noticeUsers" @select-user="onSelectUser" />
    </a-modal>
  </a-modal>
</template>

<script setup lang="ts">
import { Message } from '@arco-design/web-vue'
import { useWindowSize } from '@vueuse/core'
import AiEditor from './editor/edit/index.vue'
import { addNotice, getNotice, updateNotice } from '@/apis/system/notice'
import { listUserDict } from '@/apis'
import { type ColumnItem, GiForm } from '@/components/GiForm'
import type { LabelValueState } from '@/types/global'
import { useResetReactive } from '@/hooks'
import { useDict } from '@/hooks/app'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const { width } = useWindowSize()

const dataId = ref('')
const visible = ref(false)
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改' : '新增'))
const formRef = ref<InstanceType<typeof GiForm>>()
const { notice_type } = useDict('notice_type')

const [form, resetForm] = useResetReactive({
  title: '',
  type: '',
  effectiveTime: '',
  terminateTime: '',
  content: '',
  noticeScope: 1,
  priority: 'H',
  noticeUsers: []
})

const columns: ColumnItem[] = reactive([
  {
    label: '标题',
    field: 'title',
    type: 'input',
    props: {
      maxLength: 150,
      showWordLimit: true
    },
    rules: [{ required: true, message: '请输入标题' }]
  },
  {
    label: '类型',
    field: 'type',
    type: 'select',
    props: {
      options: notice_type
    },
    rules: [{ required: true, message: '请输入类型' }]
  },
  {
    label: '优先级',
    field: 'priority',
    type: 'radio-group',
    props: {
      options: [{ label: '高', value: 'H' }, { label: '中', value: 'M' }, { label: '低', value: 'L' }]
    },
    rules: [{ required: true, message: '请选择优先级' }]
  },
  {
    label: '生效时间',
    field: 'effectiveTime',
    type: 'date-picker',
    props: {
      showTime: true
    }
  },
  {
    label: '终止时间',
    field: 'terminateTime',
    type: 'date-picker',
    props: {
      showTime: true
    }
  },
  {
    label: '通知范围',
    field: 'noticeScope',
    type: 'radio-group',
    props: {
      options: [{ label: '所有人', value: 1 }, { label: '指定用户', value: 2 }]
    },
    rules: [{ required: true, message: '请选择通知范围' }]
  },
  {
    label: '指定用户',
    field: 'noticeUsers',
    type: 'select',
    hide: () => {
      return form.noticeScope === 1
    },
    rules: [{ required: true, message: '请选择指定用户' }]
  }
])

// 保存
const save = async () => {
  const isInvalid = await formRef.value?.formRef?.validate()
  if (isInvalid) return false
  try {
    // 通知范围 所有人 去除指定用户
    form.noticeUsers = form.noticeScope === 1 ? null : form.noticeUsers
    if (isUpdate.value) {
      await updateNotice(dataId.value, form)
      Message.success('修改成功')
    } else {
      await addNotice(form)
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    console.error(error)
    return false
  }
}

// 打开用户选择窗口
const selectUserModalVisible = ref(false)
const onOpenSelectUser = () => {
  selectUserModalVisible.value = true
}

const UserSelectRef = ref()
// 重置
const reset = () => {
  formRef.value?.formRef?.resetFields()
  UserSelectRef.value?.onClearSelected()
  resetForm()
}

// 清除
const clear = () => {
  UserSelectRef.value?.onClearSelected()
}

// 用户选择回调
const onSelectUser = (value: string[]) => {
  form.noticeUsers = value
  formRef.value?.formRef?.validateField('noticeUsers')
}

const userList = ref<LabelValueState[]>([])
onMounted(async () => {
  // 获取所有用户
  const { data } = await listUserDict({})
  userList.value = data.map((item) => ({ ...item, value: `${item.value}` }))
})

// 新增
const onAdd = () => {
  reset()
  dataId.value = ''
  visible.value = true
}

// 修改
const onUpdate = async (id: string) => {
  reset()
  dataId.value = id
  const { data } = await getNotice(id)
  Object.assign(form, data)
  visible.value = true
}

defineExpose({ onAdd, onUpdate })
</script>

<style scoped lang="less"></style>
